﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XcoAppSpaces.Core;
using XcoAppSpaces.Serialization.Json;
using System.Threading;

namespace testServer.XcoAppSpaces.SL
{
	class SpaceServer : IDisposable
	{
		private XcoAppSpace space;

		public SpaceServer(int port, bool secure)
		{
			Start(port, secure);
		}

		public void Start(int port, bool secure)
		{
			var configString = "tcp.port=" + port + ";serializer=json;ccr.threadcount=4";
			if (secure)
				configString += ";tcp.key=secure123";
			space = new XcoAppSpace(configString);
			space.Receive(space.Errors, error => Console.WriteLine("Comm ERROR from " + error.SourceAddress + ": " + error.Info));

			space.Run<SpaceMessage>(m =>
			{
				Console.WriteLine("Addition request received (" + port + "): " + m.Num1 + " + " + m.Num2);

				for (int i = 5; i <= 100; i += 5)
				{
					m.ProgressPort.Post(i);
					Thread.Sleep(50);
				}

				m.ResponsePort.Post(m.Num1 + m.Num2);
			});

			space.Run<LargeMessage>(m =>
			{
				Console.WriteLine("Large message received.");
				m.ResponsePort.Post(m.Msg);
			});

			space.Run<HighFrequencyResponseMsg>(m =>
			{
				for (int i = 0; i < 1000; i++)
				{
					m.ResponsePort.Post(i);
				}
			});

			space.Run<string>(m =>
			{
				Console.WriteLine("String message received: " + m);
			});
		}

		public void Dispose()
		{
			if (space != null)
				space.Dispose();
		}
	}
}
